package com.gitee.zeric.codec.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.zeric.codec.dto.BarCodeParamDTO;
import com.gitee.zeric.codec.dto.SysCodeRuleGenerateDTO;
import com.gitee.zeric.codec.entity.SysCodeRuleGenerate;
import com.gitee.zeric.codec.service.SysCodeRuleGenerateService;
import com.gitee.zeric.codec.util.BarcodeUtil;
import com.gitee.zeric.codec.util.TenantUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.*;

/**
 * 系统编码生成规则模块
 *
 * @author zj
 * @date 2021-12-15
 */
@RequiredArgsConstructor
@Api(value = "sysrulegenerate", tags = "系统编码生成规则模块管理v3")
@RequestMapping("/dps/api/sysrulegenerate")
@Validated
public class SysCodeRuleGenerateBaseController {
    private final SysCodeRuleGenerateService sysCodeRuleGenerateService;

    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSysRuleGeneratePage(Page<SysCodeRuleGenerate> page, SysCodeRuleGenerateDTO sysCodeRuleGenerateDTO) {
        sysCodeRuleGenerateDTO = Optional.ofNullable(sysCodeRuleGenerateDTO).orElse(new SysCodeRuleGenerateDTO());
        List<Integer> fan = new ArrayList<>();
        fan.add(-1);
        if (sysCodeRuleGenerateDTO.getPrivateOrg() != null) {
            fan.add(sysCodeRuleGenerateDTO.getPrivateOrg());
        }
        LambdaQueryWrapper<SysCodeRuleGenerate> queryWrapper =
                new LambdaQueryWrapper<SysCodeRuleGenerate>()
                        .and(s -> s.eq(SysCodeRuleGenerate::getTenantId, TenantUtils.getTenantId())
                                .or().eq(SysCodeRuleGenerate::getRuleType, "0"))
                        .in(SysCodeRuleGenerate::getPrivateOrg, fan).orderByAsc(SysCodeRuleGenerate::getRuleType);
        if (StrUtil.isNotBlank(sysCodeRuleGenerateDTO.getName())) {
            queryWrapper.like(SysCodeRuleGenerate::getName, sysCodeRuleGenerateDTO.getName());
        }
        if (StrUtil.isNotBlank(sysCodeRuleGenerateDTO.getBusinessType())) {
            queryWrapper.eq(SysCodeRuleGenerate::getBusinessType, sysCodeRuleGenerateDTO.getBusinessType());
        }
        //默认查询常量与自定义
        if (StrUtil.isBlank(sysCodeRuleGenerateDTO.getRuleType())) {
            queryWrapper.in(SysCodeRuleGenerate::getRuleType, Arrays.asList("1", "2"));
        } else {
            queryWrapper.in(SysCodeRuleGenerate::getRuleType, Collections.singletonList(sysCodeRuleGenerateDTO.getRuleType()));
        }
        Page<SysCodeRuleGenerate> ruleGeneratePage = sysCodeRuleGenerateService.page(page,
                queryWrapper);
        Page<SysCodeRuleGenerateDTO> ruleGeneratePageDto = new Page<>(ruleGeneratePage.getCurrent(), ruleGeneratePage.getSize(), ruleGeneratePage.getTotal());
        ruleGeneratePageDto.setRecords(BeanUtil.copyToList(ruleGeneratePage.getRecords(), SysCodeRuleGenerateDTO.class));
        return R.ok(ruleGeneratePageDto);
    }

    @GetMapping("/search")
    public R getSysRuleGenerates(SysCodeRuleGenerate sysRuleGenerate) {
        List<SysCodeRuleGenerate> ruleGenerates = sysCodeRuleGenerateService.list(Wrappers.query(sysRuleGenerate));
        return R.ok(BeanUtil.copyToList(ruleGenerates, SysCodeRuleGenerateDTO.class));
    }

    @ApiOperation(value = "批量编码生成", notes = "批量编码生成")
    @GetMapping("/batchGenerate")
    public R batchGenerate(@RequestParam String ruleCode, @Min(value = 1, message = "size参数最小值为1") @RequestParam Integer size) {
        return R.ok(this.sysCodeRuleGenerateService.batchGet(ruleCode, size));
    }

    @ApiOperation(value = "批量编码功能测试", notes = "批量编码功能测试")
    @GetMapping("/functionBatchTest")
    public R functionTestBatch(@RequestParam String ruleCode, @Min(value = 1, message = "size参数最小值为1") @RequestParam Integer size) {
        return R.ok(this.sysCodeRuleGenerateService.functionTestBatch(ruleCode, size));
    }

    @ApiOperation(value = "功能预测试", notes = "功能预测试")
    @PostMapping("/functionTest")
    public R functionForeseeTest(@RequestBody @Valid SysCodeRuleGenerateDTO sysCodeRuleGenerateDto) {
        return R.ok(this.sysCodeRuleGenerateService.functionForeseeTest(BeanUtil.copyProperties(sysCodeRuleGenerateDto, SysCodeRuleGenerate.class), null));
    }

    @ApiOperation(value = "条形码/二维码生成", notes = "条形码/二维码生成")
    @GetMapping("/barCode/generate")
    public R getbarCode(BarCodeParamDTO barCodeParamDTO) {
        String baseCode = "";
        try {
            //条形码
            if (barCodeParamDTO.getType() == 0) {
                baseCode = BarcodeUtil.generateBarCodeBase64(barCodeParamDTO.getCode(), barCodeParamDTO.getFormat(),
                        barCodeParamDTO.getDpi(), barCodeParamDTO.getHeight());
            } else {
                //二维码
                baseCode = BarcodeUtil.generateQrCodeBase64(barCodeParamDTO.getCode(), barCodeParamDTO.getWidth(), barCodeParamDTO.getHeight());
            }
            return R.ok(baseCode);
        } catch (Exception e) {
            return R.failed("服务异常");
        }
    }


    /**
     * 通过id查询系统编码生成规则模块
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        SysCodeRuleGenerate ruleGenerate = sysCodeRuleGenerateService.getById(id);
        return R.ok(ruleGenerate);
    }

    /**
     * 新增系统编码生成规则模块
     *
     * @param sysCodeRuleGenerateDto 系统编码生成规则模块
     * @return R
     */
    @ApiOperation(value = "新增系统编码生成规则模块", notes = "新增系统编码生成规则模块")
    @PostMapping
    public R save(@RequestBody @Valid SysCodeRuleGenerateDTO sysCodeRuleGenerateDto) {
        Integer tenantId = TenantUtils.getTenantId();
        sysCodeRuleGenerateDto.setRuleCode(tenantId + ":" + sysCodeRuleGenerateDto.getRuleCode().toUpperCase().replace(":", "_"));
        //TENANT_ID放在请求头中传过来的，这里手动设置实体后保存到数据库中
        sysCodeRuleGenerateDto.setTenantId(tenantId);
        return sysCodeRuleGenerateService.saveWithRedis(BeanUtil.copyProperties(sysCodeRuleGenerateDto, SysCodeRuleGenerate.class));
    }

    /**
     * 修改系统编码生成规则模块
     *
     * @param sysCodeRuleGenerateDto 系统编码生成规则模块
     * @return R
     */
    @ApiOperation(value = "修改系统编码生成规则模块", notes = "修改系统编码生成规则模块")
    @PutMapping
    public R updateById(@RequestBody @Valid SysCodeRuleGenerateDTO sysCodeRuleGenerateDto) {
        sysCodeRuleGenerateDto.setRuleCode(sysCodeRuleGenerateDto.getRuleCode().toUpperCase());
        //TENANT_ID放在请求头中传过来的，这里手动设置实体后保存到数据库中
        sysCodeRuleGenerateDto.setTenantId(TenantUtils.getTenantId());
        return sysCodeRuleGenerateService.updateWithRedisById(BeanUtil.copyProperties(sysCodeRuleGenerateDto, SysCodeRuleGenerate.class));
    }

    /**
     * 通过id删除系统编码生成规则模块
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除系统编码生成规则模块", notes = "通过id删除系统编码生成规则模块")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Integer id) {
        return sysCodeRuleGenerateService.removeWithRedisById(id);
    }


}
